<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="设备名称" prop="name">
        <ns-input v-model="formData.name" placeholder="请输入设备名称" />
      </el-form-item>
      <!-- <el-form-item label="关联系统" prop="infoSystemId">
        <el-cascader
          v-model="formData.infoSystemId"
          placeholder="请选择归属系统"
          :props="systemCascaderProps"
          :options="systemList"
          filterable
          clearable
        />
      </el-form-item>
      <el-form-item label="归属机构" prop="deptId">
        <el-cascader
          v-model="formData.deptId"
          clearable
          placeholder="请选择归属机构"
          :options="deptList"
          :props="cascaderProps"
          filterable
        />
      </el-form-item>
      <el-form-item label="IP地址" prop="ip">
        <ns-input v-model="formData.ip" placeholder="请输入IP地址" />
      </el-form-item>
      <el-form-item label="端口" prop="port">
        <ns-input v-model="formData.port" placeholder="请输入端口" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <ns-input v-model="formData.type" placeholder="请输入类型" />
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <ns-input v-model="formData.account" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="passwd">
        <ns-input v-model="formData.passwd" placeholder="请输入密码称" />
      </el-form-item>
      <el-form-item label="区域选择" prop="areas">
        <el-cascader
          clearable
          :options="pcaTextArr"
          v-model="formData.areas"
          placeholder="请选择区域"
        />
      </el-form-item>
      <el-form-item label="地理位置" prop="address">
        <ns-input v-model="formData.address" placeholder="请输入地理位置" />
      </el-form-item>  -->
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { handleTree } from '@/utils/tree'
import { pcaTextArr } from 'element-china-area-data'
import * as DeviceApi from '@/api/device'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  infoSystemId: undefined,
  deptId: '',
  ip: undefined,
  port: undefined,
  type: undefined,
  account: undefined,
  passwd: undefined,
  areas: undefined,
  address: undefined,
  isDeleted: 0,
  status: '1'
})
const formRules = reactive({
  name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  infoSystemId: [{ required: true, message: '关联系统不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '归属机构不能为空', trigger: 'blur' }],
  ip: [{ required: true, message: 'IP地址不能为空', trigger: 'blur' }],
  port: [{ required: true, message: '端口不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
  account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  passwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await DeviceApi.deviceGet(id)
      formData.value = data
      formData.value.deptId = Number(data.deptId)
    } finally {
      formLoading.value = false
    }
  }
  getSystemList()
  getDeptList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await DeviceApi.deviceCreate(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.deviceUpdate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    infoSystemId: undefined,
    deptId: undefined,
    ip: undefined,
    port: undefined,
    type: undefined,
    account: undefined,
    passwd: undefined,
    areas: undefined,
    address: undefined,
    isDeleted: 0,
    status: '1'
  }
  formRef.value?.resetFields()
}

const systemList = ref([{}])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

const deptList = ref([{}])
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  deptList.value = data
}
</script>
